/****************************************************************
Program: Lawyers_Master.do
Authors: Agan, Freedman, & Owens
Paper: Is Your Lawyer a Lemon (Review of Economics and Statistics)
Updated: July 1, 2019
Description: Program to generate descriptive statistics; also 
	calls Lawyers_Regressions.do to run main regressions and
	Gelbach decompositions.
Data Requirements: Requires Lawyers_CourtData.dta 
	be located in same folder as program files.
Software: Originally run in Stata-MP 14.2.
Other Notes: Calls on reghdfe.ado (version 3.2.9 21feb2016).
****************************************************************/
cap log close
log using "Lawyers_Master `c(current_date)'", t replace
clear all
set matsize 11000
set maxvar 32767
set more off

use Lawyers_CourtData.dta, clear

*** Figure 1 ***

* Figure 1a
gen exp_fig=experience if experience>=0 & experience!=.
replace exp_fig=35 if experience>=35 & experience!=.
by attybarcard exp_fig, sort: egen pct_appt_exp=mean(appointed)
by attybarcard exp_fig, sort: gen n_attyexp=_n
gen pct2=pct_appt_exp if n_attyexp==1
by exp_fig, sort: egen mean_pct=mean(pct2) 
line mean_pct exp_fig, xtitle("Years since Attorney Passed Bar") ytitle("Fraction Cases Assigned") ///
	scheme(s1mono) ylab(, nogrid) xscale(range(0(5)35)) xlabel(0(5)35) 
graph export Figure1a.pdf, replace

* Figure 1c
bysort attorneybarnbr complaintyear: egen pct_appt_year=mean(appointed)
bysort attorneybarnbr complaintyear: gen n_atty_year=_n
gen both_year=pct_appt_year>0 & pct_appt_year<1
sum pct_appt_year if both_year==1 & n_atty_year==1
tw kdensity pct_appt_year if n_atty_year==1 & both_year==1 || kdensity pct_appt_year if n_atty_year==1 & both_year==1 & experience<5, lpattern(shortdash) ///
  || kdensity pct_appt_year if n_atty_year==1 & both_year==1 & experience>25, lpattern(longdash) ///
   xtitle("Fraction Cases Assigned") ytitle("Density") 	scheme(s1mono) legend(label(1 "All") label(2 "<5 Years Exp.") label(3 ">25 Years Exp.") region(style(none)) col(3))
graph export "Figure1c.pdf", replace

* Figure 1b
gen onlyretained=(pct_appt_exp==0)
gen retain=onlyretained if n_attyexp==1
bysort exp_fig: egen mean_onlyretain=mean(retain) 
line mean_onlyretain exp_fig, xtitle("Years since Attorney Passed Bar") ///
	ytitle("Probability No Assigned Cases") ///
	scheme(s1mono) ylab(, nogrid)  xscale(range(0(5)35)) xlabel(0(5)35)   
graph export Figure1b.pdf, replace
drop exp_fig pct_appt_exp n_attyexp mean_pct pct_appt_year n_atty_year both_year onlyretained retain mean_onlyretain

*** Table 1 ***

	* Fee Schedule for Assigned Counsel in Bexar County
	* Adapted from State of Texas and County of Bexar, "Joint Order Adopting Fee Schedule" 
	* September 3, 2004, Document 58349; July 6, 2009, Document 62328; October 14, 2015, Document 67837. 

*** Table 2 ***

* Create Macros for Table Rows
	local defendant "male age_offense white black hisp num_charges convict_hist hadbondsman povrate instability"
	local case "state_jail F_2_3 F_1 violent property drug"
	local atty "experience attymale distance_to_atty atty_exp  pct_appt racematch"
	local outcomes "reduced dismissed defadj plead_guilty plead_nolo guilty incarcerated uncond_sent totalfine"

* Generate Table 2
	estpost tabstat `defendant' `case' `atty' `outcomes', by(appointed) ///
		statistics(mean sd) listwise columns(statistics) nototal
	 esttab using Table2.csv, csv main(mean) aux(sd) unstack  nonote ///
	   nonumber onecell label nogap replace 


*** Table 3 ***

eststo clear
foreach var in racematch male distance_to_atty atty_exp experience percent_cases_offense_specific {
  	estpost ttest `var', by(appointed)
}
foreach race in black hisp white {
	di "`race'"
	foreach var in racematch male distance_to_atty atty_exp  experience percent_cases_offense_specific {
		estpost ttest `var' if `race'==1, by(appointed)
	}
}

*** Figure 4 and Figure A2***
	
	egen atty=group(attorneybarnbr)
	sum atty
	local attys=r(max)
	xi: reghdfe guilty appointed#i.atty male age_offense complaint_hist convict_hist hadbondsman i.race povrate instability lndist atty_exp pct_appt racematch caseload_retained_30 if used==1 & gjuryyear>2000 & !mi(typeofoffense) ,  absorb(atty_year offense_num court_docket) old
	gen guilty_attybeta=.
	forv a=1(1)`attys' {
		capture local b=_b[1.appointed#`a'.atty]
		if _rc==0 {
			replace guilty_attybeta=_b[1.appointed#`a'.atty] if atty==`a'
		}
	}
	xi: reg recid_felony_3year male age_offense complaint_hist convict_hist hadbondsman i.race povrate instability if incarcerated==0
	predict recid_resid, resid
	gen x_a=recid_resid if appointed==1 & incarcerated==0
	gen x_b=recid_resid if appointed==0 & incarcerated==0
	bysort attybarcard: egen hold_1=mean(x_a)
	bysort attybarcard: egen hold_2=mean(x_b)
	bysort attybarcard: egen shr_assigned=mean(appointed)
	gen shr_assigned_i=shr_assigned*(1-shr_assigned)
	bysort attybarcard: gen atty_n=_n
	reg hold_1 guilty_attybeta if atty_n==1 [w=shr_assigned_i]
	local beta : di %4.3f _b[guilty_attybeta]
	local se: di %4.3f _se[guilty_attybeta]
	twoway (scatter hold_1 guilty_attybeta if atty_n==1 [w=shr_assigned_i], mfcolor(white) msize(tiny)) (lfit hold_1 guilty_attybeta if atty_n==1 [w=shr_assigned_i]), caption("Beta=`beta', se=`se'") scheme(s1mono) legend(off) xtitle(Attorney Penalty) ytitle(Recidivism)
	graph export "Figure4.pdf", replace	
	reg hold_2 guilty_attybeta if atty_n==1 [w=shr_assigned_i]
	local beta : di %4.3f _b[guilty_attybeta]
	local se: di %4.3f _se[guilty_attybeta]
	twoway (scatter hold_2 guilty_attybeta if atty_n==1 [w=shr_assigned_i], mfcolor(white) msize(tiny)) (lfit hold_2 guilty_attybeta if atty_n==1 [w=shr_assigned_i]), caption("Beta=`beta', se=`se'") scheme(s1mono) legend(off) xtitle(Attorney Penalty) ytitle(Recidivism)
	graph export "FigureA2.pdf", replace	
	drop atty recid* shr_assigned shr_assigned_i hold* guilty_attybeta
	
*** Appendix Tables A1, A2, A4, A5  ***

* Macros for Descriptive Statistics Tables (Table A4)
	local defendant "male age_offense white black hisp num_charges convict_hist hadbondsman povrate instability"
	local case "state_jail F_2_3 F_1 violent property drug"
	local atty "experience attymale distance_to_atty atty_exp  pct_appt racematch"
	local outcomes "reduced dismissed defadj plead_guilty plead_nolo guilty incarcerated uncond_sent totalfine"	

* Table A1, A2, A5(A). Baseline OLS Estimates
use Lawyers_CourtData.dta, clear
	global samp="Base"
	tab appointed
	tab guilty
	estpost tabstat `defendant' `case' `atty' `outcomes', by(appointed) ///
		statistics(mean sd) listwise columns(statistics) nototal
	qui do Lawyers_Regressions.do

* Table A5(B). Minor Offenses
use Lawyers_CourtData.dta, clear
	keep if offensetype=="F3" | offensetype=="FS"
	global samp="Minor"
	tab appointed
	tab guilty
	estpost tabstat `defendant' `case' `atty' `outcomes', by(appointed) ///
		statistics(mean sd) listwise columns(statistics) nototal
	esttab using TableA4_$samp.csv, csv main(mean) aux(sd) unstack  nonote ///
		nonumber onecell label nogap replace 
	qui do Lawyers_Regressions

* Table A5(C). Minor Drug Offenses	
use Lawyers_CourtData.dta, clear
	keep if offensecat=="drug" & index(offensedesc, "POSS")>0 & index(offensedesc, "LESS THAN")>0
	global samp="DrugPoss"
	tab appointed
	tab guilty
	estpost tabstat `defendant' `case' `atty' `outcomes', by(appointed) ///
		statistics(mean sd) listwise columns(statistics) nototal
	esttab using TableA4_$samp.csv, csv main(mean) aux(sd) unstack  nonote ///
		nonumber onecell label nogap replace 
	qui do Lawyers_Regressions

* Table A5(D). Low-Income Block Groups
use Lawyers_CourtData.dta, clear
	keep if poor==1
	global samp="Poor"
	tab appointed
	tab guilty
	estpost tabstat `defendant' `case' `atty' `outcomes', by(appointed) ///
		statistics(mean sd) listwise columns(statistics) nototal
	esttab using TableA4_$samp.csv, csv main(mean) aux(sd) unstack  nonote ///
		nonumber onecell label nogap replace 
	qui do Lawyers_Regressions	

* Table A5(E). Less Than 5 Yrs Experience
use Lawyers_CourtData.dta, clear
	keep if experience<=5
	global samp="lt5"
	tab appointed
	tab guilty
	estpost tabstat `defendant' `case' `atty' `outcomes', by(appointed) ///
		statistics(mean sd) listwise columns(statistics) nototal
	esttab using TableA4_$samp.csv, csv main(mean) aux(sd) unstack  nonote ///
		nonumber onecell label nogap replace 
	qui do Lawyers_Regressions

* Table A5(F). Local Attorneys
use Lawyers_CourtData.dta, clear
	keep if trim(upper(attycity))=="SAN ANTONIO"
	global samp="Local"
	tab appointed
	tab guilty
	estpost tabstat `defendant' `case' `atty' `outcomes', by(appointed) ///
		statistics(mean sd) listwise columns(statistics) nototal
	esttab using TableA4_$samp.csv, csv main(mean) aux(sd) unstack  nonote ///
		nonumber onecell label nogap replace 
	qui do Lawyers_Regressions

* Table A5(G). Excl MTRs
use Lawyers_CourtData.dta, clear
	keep if trim(revokationprosecutor)==""
	global samp="NoRevoke"
	tab appointed
	tab guilty
	estpost tabstat `defendant' `case' `atty' `outcomes', by(appointed) ///
		statistics(mean sd) listwise columns(statistics) nototal
	esttab using TableA4_$samp.csv, csv main(mean) aux(sd) unstack  nonote ///
		nonumber onecell label nogap replace 
	qui do Lawyers_Regressions

* Table A5(H). A-Ys with Both Assigned and Retained Cases
use Lawyers_CourtData.dta, clear
	bysort atty_year: egen shr_assigned=mean(appointed)
	keep if shr_assigned>0 & shr_assigned<1
	count
	global samp="BothCaseTypes"
	tab appointed
	tab guilty
	estpost tabstat `defendant' `case' `atty' `outcomes', by(appointed) ///
		statistics(mean sd) listwise columns(statistics) nototal
	esttab using TableA4_$samp.csv, csv main(mean) aux(sd) unstack  nonote ///
		nonumber onecell label nogap replace 
	qui do Lawyers_Regressions

* Table A5(I). Lasso Model	
* (run within baseline results in part A5(A).)	

* Table A5(J). Interactions with Social Capital
* (run within baseline results in part A5(A).)	

* Table A5(K). IV Estimates
* (run within baseline results in part A5(A))	

	
*** Figure 3 ***

use Lawyers_CourtData.dta, clear
	qui do Lawyers_Time	


*** Gelbach Decompositions (Figure 2, Appendix Figure A1, and Appendix Table A3) ***	

use Lawyers_CourtData.dta, clear

capture drop typeofoffense_num

gen obscount=_n
xi i.court_docket, prefix(_CD)
xi i.race i.offense_num, prefix(_CO)
qui tab atty_year, gen(ay)

# delimit ;
foreach outcome in incarcerated lnsent lnfine {;

	foreach cvar in attybarcard {;

		qui b1x2 `outcome' if used==1 & gjuryyear>2000 & !mi(typeofoffense) & guilty==1 , 
			x1all(appointed) x2all(male age_offense povrate instability complaint_hist convict_hist hadbondsman _C* lndist atty_exp pct_appt racematch caseload_retained_30 ay* ) 
			x1only(appointed) 
			nobase nofull
			x2delta( client =  male age_offense povrate instability complaint_hist convict_hist hadbondsman _C* : 
			atty_chars = lndist atty_exp pct_appt racematch caseload_retained_30 ay*) cluster(`cvar');

		mat D=e(b1base);
		mat DV`cvar'=e(V1base);
		mat B=e(b);
		mat V`cvar'=e(V);
		mat R=e(b1full);
		mat RV`cvar'=e(V1full);
	};

	mat DV=DVattybarcard;
	mat RV=RVattybarcard;
	mat V=Vattybarcard;
	# delimit ;

	sort obscount;

	gen `outcome'_gtype="Uncond" if _n==1;		
	replace `outcome'_gtype="Case" if _n==2;
	replace `outcome'_gtype="Atty" if _n==3;
	replace `outcome'_gtype="Cond" if _n==4;
	
	gen `outcome'_ght=D[1,1] if _n==1;
	gen `outcome'_gse=DV[1,1] if _n==1;
	
	replace `outcome'_ght=R[1,1] if _n==4;
	replace `outcome'_gse=RV[1,1] if _n==4;
	# delimit ;

	forvalues n=1(1)2{;
		local nn=`n'+1;
		replace `outcome'_ght=B[1,`n'] if _n==`nn';
		replace `outcome'_gse=V[`n',`n'] if _n==`nn';
		};

		replace `outcome'_gse=`outcome'_gse^.5;

		gen `outcome'_gpct=`outcome'_ght/D[1,1];

};	

# delimit;
export excel incarcerated_gtype incarcerated_ght incarcerated_gse lnsent_ght lnsent_gse lnfine_ght lnfine_gse incarcerated_gpct 
	lnsent_gpct lnfine_gpct if incarcerated_gtype!="" using FigureGelbach_Guilty, replace first(var);

# delimit;
foreach outcome in guilty dismissed defadj plead_guilty plead_nolo incarcerated reduced lnsent lnfine  {;
	
	foreach cvar in attybarcard {;

		qui b1x2 `outcome' if used==1 & gjuryyear>2000 & !mi(typeofoffense) , 
		x1all(appointed) x2all(male age_offense povrate instability complaint_hist convict_hist hadbondsman _C* lndist atty_exp pct_appt racematch caseload_retained_30  ay*) 
		x1only(appointed) 
		nobase nofull
		x2delta( client =  male age_offense povrate instability complaint_hist convict_hist hadbondsman _C* : 
		atty_chars = lndist atty_exp pct_appt racematch caseload_retained_30   ay*) cluster(`cvar');

		mat D=e(b1base);
		mat DV`cvar'=e(V1base);
		mat B=e(b);
		mat V`cvar'=e(V);
		mat R=e(b1full);
		mat RV`cvar'=e(V1full);
	};

	mat DV=DVattybarcard;
	mat RV=RVattybarcard;
	mat V=Vattybarcard;

	sort obscount;

	gen `outcome'_type="Uncond" if _n==1;		
	replace `outcome'_type="Case" if _n==2;
	replace `outcome'_type="Atty" if _n==3;
	replace `outcome'_type="Cond" if _n==4;

	gen `outcome'_ht=D[1,1] if _n==1;
	gen `outcome'_se=DV[1,1] if _n==1;
	
	replace `outcome'_ht=R[1,1] if _n==4;
	replace `outcome'_se=RV[1,1] if _n==4;
	
	forvalues n=1(1)2{;
		local nn=`n'+1;
		replace `outcome'_ht=B[1,`n'] if _n==`nn';
		replace `outcome'_se=V[`n',`n'] if _n==`nn';
		};

		replace `outcome'_se=`outcome'_se^.5;

		gen `outcome'_pct=`outcome'_ht/D[1,1];
 };		
 
 
 
 # delimit;
export excel incarcerated_type 
	guilty_ht guilty_se guilty_pct
	dismissed_ht dismissed_se dismissed_pct 
	defadj_ht defadj_se defadj_pct 
	plead_guilty_ht plead_guilty_se plead_guilty_pct
	plead_nolo_ht plead_nolo_se plead_nolo_pct 
	incarcerated_ht incarcerated_se incarcerated_pct 
	reduced_ht reduced_se reduced_pct
	lnsent_ht lnsent_se lnsent_pct 
	lnfine_ht lnfine_se lnfine_pct 
	if incarcerated_type!="" using FigureGelbach_Unconditional, replace first(var);


# delimit;
foreach outcome in guilty dismissed defadj plead_guilty plead_nolo incarcerated reduced lnsent lnfine  {;
	putexcel set TableA3_`outcome', replace;	

	foreach cvar in attybarcard {;

		b1x2 `outcome' if used==1 & gjuryyear>2000 & !mi(typeofoffense) , 
		x1all(appointed) x2all(male age_offense povrate instability complaint_hist convict_hist hadbondsman _C* lndist atty_exp pct_appt racematch caseload_retained_30 ay*) 
		x1only(appointed) 
		nobase nofull
		 x2delta( 
		offense = _COo*:
		court = _CD*:
		male = male:
		age_offense = age_offense:
		client_race = _COr*:
		complaint_hist =complaint_hist:
		convict_hist = convict_hist:
		hadbondsman = hadbondsman:
		povrate = povrate:
		instability = instability:
		lndist = lndist:
		atty_exp = atty_exp :
		pct_appt = pct_appt :
		racematch = racematch :
		caseload_retained_30 = caseload_retained_30 :
		attorney_FE =  ay*:
		)  cluster(`cvar');

		mat D=e(b1base);
		mat DV`cvar'=e(V1base);
		mat B=e(b)';
		mat V`cvar'=e(V);
		mat R=e(b1full);
		mat RV`cvar'=e(V1full);
	};

	mat DV=DVattybarcard;
	mat RV=RVattybarcard;
	mat V=Vattybarcard;

	mat V2=V';

	putexcel A1 = matrix(B), rownames ;
	putexcel D1 = matrix(V2), rownames;

 };		
 # delimit ;
 set more off;
 
foreach outcome in incarcerated lnsent lnfine {;
	putexcel set TableA3_`outcome'_Guilty, replace;
	
	foreach cvar in attybarcard {;

		b1x2 `outcome' if used==1 & gjuryyear>2000 & !mi(typeofoffense) & guilty==1 , 
		x1all(appointed) x2all(male age_offense povrate instability complaint_hist convict_hist hadbondsman _C* lndist atty_exp pct_appt racematch caseload_retained_30 ay* ) 
		x1only(appointed) 
		nobase nofull
		x2delta( 
		offense = _COo*:
		court = _CD*:
		male = male:
		age_offense = age_offense:
		client_race = _COr*:
		complaint_hist =complaint_hist:
		convict_hist = convict_hist:
		hadbondsman = hadbondsman:
		povrate = povrate:
		instability = instability:
		lndist = lndist:
		atty_exp = atty_exp :
		pct_appt = pct_appt :
		racematch = racematch :
		caseload_retained_30 = caseload_retained_30 :
		attorney_FE = ay*:
		)  cluster(`cvar');

	mat D=e(b1base);
	mat DV`cvar'=e(V1base);
	mat B=e(b)';
	mat V`cvar'=e(V);
	mat RV`cvar'=e(V1full);
	mat R=e(b1full);
	};

	mat DV=DVattybarcard;
	mat RV=RVattybarcard;
	mat V=Vattybarcard;
	mat V2=V';
	putexcel A1 = matrix(B), rownames ;
	putexcel D1 = matrix(V2), rownames;
};	

# delimit;
drop if MTR==1;
foreach outcome in 0 1 {;

foreach cvar in attybarcard {;

	qui b1x2 case_length if used==1 & hadbondsman==`outcome' & gjuryyear>2000 & !mi(typeofoffense) , 
	x1all(appointed) x2all(male age_offense povrate instability complaint_hist convict_hist hadbondsman _C* lndist atty_exp pct_appt racematch caseload_retained_30 ay* ) 
	x1only(appointed) 
	nobase nofull
	x2delta( client =  male age_offense povrate instability complaint_hist convict_hist hadbondsman _C* : 
	atty_chars = lndist atty_exp pct_appt racematch caseload_retained_30  ay*) cluster(`cvar');

	mat D=e(b1base);
	mat DV`cvar'=e(V1base);
	mat B=e(b);
	mat V`cvar'=e(V);
	mat R=e(b1full);
	mat RV`cvar'=e(V1full);
};

mat DV=DVattybarcard;
mat RV=RVattybarcard;
mat V=Vattybarcard;

sort obscount;

	gen _`outcome'_type="Uncond" if _n==1;		
	replace _`outcome'_type="Case" if _n==2;
	replace _`outcome'_type="Atty" if _n==3;
	replace _`outcome'_type="Cond" if _n==4;
	
	gen _`outcome'_ht=D[1,1] if _n==1;
	gen _`outcome'_se=DV[1,1] if _n==1;
	
	replace _`outcome'_ht=R[1,1] if _n==4;
	replace _`outcome'_se=RV[1,1] if _n==4;
	
	forvalues n=1(1)2{;
		local nn=`n'+1;
		replace _`outcome'_ht=B[1,`n'] if _n==`nn';
		replace _`outcome'_se=V[`n',`n'] if _n==`nn';
		};

		replace _`outcome'_se=_`outcome'_se^.5;

		gen _`outcome'_pct=_`outcome'_ht/D[1,1];
 };		
  
 foreach cvar in attybarcard {;

	qui b1x2 case_length if used==1 & gjuryyear>2000 & !mi(typeofoffense) , 
	x1all(appointed) x2all(male age_offense povrate instability  complaint_hist convict_hist hadbondsman _C* lndist atty_exp pct_appt racematch caseload_retained_30 ay* ) 
	x1only(appointed) 
	nobase nofull
	x2delta( client =  male age_offense povrate instability complaint_hist convict_hist hadbondsman _C* : 
	atty_chars = lndist atty_exp pct_appt racematch caseload_retained_30  ay*) cluster(`cvar');

	mat D=e(b1base);
	mat DV`cvar'=e(V1base);
	mat B=e(b);
	mat V`cvar'=e(V);
	mat R=e(b1full);
	mat RV`cvar'=e(V1full);
};

mat DV=DVattybarcard;
mat RV=RVattybarcard;
mat V=Vattybarcard;

sort obscount;

	gen caselength_type="Uncond" if _n==1;		
	replace caselength_type="Case" if _n==2;
	replace caselength_type="Atty" if _n==3;
	replace caselength_type="Cond" if _n==4;
	
	gen caselength_ht=D[1,1] if _n==1;
	gen caselength_se=DV[1,1] if _n==1;
	
	replace caselength_ht=R[1,1] if _n==4;
	replace caselength_se=RV[1,1] if _n==4;
	
	forvalues n=1(1)2{;
		local nn=`n'+1;
		replace caselength_ht=B[1,`n'] if _n==`nn';
		replace caselength_se=V[`n',`n'] if _n==`nn';
		};

		replace caselength_se=caselength_se^.5;

		gen caselength_pct=caselength_ht/D[1,1];
 
# delimit;
export excel caselength_* _0* _1* if _0_type!="" using FigureGelbach_CaseLength, replace first(var);

# delimit;

foreach outcome in 0 1 {;
	
	putexcel set TableA3_CaseLength`outcome', replace;

	foreach cvar in attybarcard {;

		qui b1x2 case_length if used==1 & hadbondsman==`outcome' & gjuryyear>2000 & !mi(typeofoffense) , 
		x1all(appointed) x2all(male age_offense povrate instability  complaint_hist convict_hist _C* lndist atty_exp pct_appt racematch caseload_retained_30  ay* ) 
		x1only(appointed) 
		nobase nofull
		 x2delta( 
		offense = _COo*:
		court = _CD*:
		male = male:
		age_offense = age_offense:
		client_race = _COr*:
		complaint_hist =complaint_hist:
		convict_hist = convict_hist:
		povrate = povrate:
		instability = instability:
		lndist = lndist:
		atty_exp = atty_exp :
		pct_appt = pct_appt :
		racematch = racematch :
		caseload_retained_30 = caseload_retained_30 :
		attorney_FE =  ay*:
		) cluster(`cvar');

		mat D=e(b1base);
		mat DV`cvar'=e(V1base);
		mat B=e(b)';
		mat V`cvar'=e(V);
		mat R=e(b1full);
		mat RV`cvar'=e(V1full);
	};

	mat DV=DVattybarcard;
	mat RV=RVattybarcard;
	mat V=Vattybarcard;

	mat V2=V';

	putexcel A1 = matrix(B), rownames ;
	putexcel D1 = matrix(V2), rownames;

};		
 
# delimit;

putexcel set TableA3_CaseLength, replace;

foreach cvar in attybarcard {;

	qui b1x2 case_length if used==1 & gjuryyear>2000 & !mi(typeofoffense) , 
	x1all(appointed) x2all(male age_offense povrate instability complaint_hist convict_hist hadbondsman _C* lndist atty_exp pct_appt racematch caseload_retained_30  ay* ) 
	x1only(appointed) 
	nobase nofull
	 x2delta( 
	offense = _COo*:
	court = _CD*:
	male = male:
	age_offense = age_offense:
	client_race = _COr*:
	complaint_hist =complaint_hist:
	convict_hist = convict_hist:
	hadbondsman = hadbondsman:
	povrate = povrate:
	instability = instability:
	lndist = lndist:
	atty_exp = atty_exp :
	pct_appt = pct_appt :
	racematch = racematch :
	caseload_retained_30 = caseload_retained_30 :
	attorney_FE =  ay*:
	) cluster(`cvar');

	mat D=e(b1base);
	mat DV`cvar'=e(V1base);
	mat B=e(b)';
	mat V`cvar'=e(V);
	mat R=e(b1full);
	mat RV`cvar'=e(V1full);
};

mat DV=DVattybarcard;
mat RV=RVattybarcard;
mat V=Vattybarcard;

mat V2=V';

putexcel A1 = matrix(B), rownames ;
putexcel D1 = matrix(V2), rownames;

#delimit cr

* Generate Gelbach Decomposition Figures (Figure 2 and Appendix Figure A1)*

clear
import excel using FigureGelbach_Guilty, first

	foreach n in incarcerated lnsent lnfine {
		gen `n'_gup=`n'_ght+(1.96*`n'_gse)
		gen `n'_gdown=`n'_ght-(1.96*`n'_gse)
		gen `n'_pctfmt = string(100 * `n'_gpct, "%8.0f") + "%"
		replace  `n'_pctfmt="("+`n'_pctfmt + ")"
	}

	gen type=1 if incarcerated_gtype=="Uncond"
	replace type=2 if incarcerated_gtype=="Case"
	replace type=3 if incarcerated_gtype=="Atty"
	replace type=4 if incarcerated_gtype=="Cond"

	label def typelabel 1 "Uncond. Penalty" 2 "Case Chars." 3 "Attorney Chars." 4 "Residual Penalty"

	label values type typelabel

	foreach outc in incarcerated lnsent lnfine {
		format `outc'_ght %12.2f 
	}

	#delimit ;
	local incarcerated_title "Incarceration | Convc.";
	local lnsent_title "Sentence Length | Convc.";
	local lnfine_title "Fine Amount | Convic.";

	set scheme s1mono;
	foreach outc in incarcerated lnsent lnfine {;
		
		sum `outc'_pct , meanonly;
		local label=r(mean);
		
		twoway bar `outc'_ght type if incarcerated_gtype=="Case" | incarcerated_gtype=="Atty" ,
			xlabel(1 2 3 4 , valuelabel ) || 
			bar `outc'_ght type if incarcerated_gtype=="Uncond"    || 
			bar `outc'_ght type if incarcerated_gtype=="Cond"   ||
			scatter  `outc'_ght type  if type!=1 , msym(none) mlab(`outc'_pctfmt) mlabpos(1)  mlabs(medlarge)||
			scatter  `outc'_ght type, msym(none) mlab(`outc'_ght) mlabpos(11) mlabs(medlarge)  ||
			rcap `outc'_gup `outc'_gdown type, lcolor(black) mcolor(black) ,
			legend(off)
			title(``outc'_title')
			ytitle("Assigned Counsel Penalty")
			xtitle("");
			graph save FigureGelbach_`outc'_G.gph, replace;

	};

#delimit cr	

import excel using FigureGelbach_Unconditional, first clear

	local reduced_title "Charge Reduced"
	local dismissed_title "Case Dismissed"
	local defadj_title "Def. Adjudication"
	local plead_nolo_title "Plead Nolo"
	local plead_guilty_title "Plead Guilty"
	local guilty_title "Convicted"
	local incarcerated_title "Incarceration"
	local lnsent_title "Sentence Length"
	local lnfine_title "Fine Amount"
	local case_length_title "Case Length"
		
	foreach n in reduced dismissed defadj plead_nolo plead_guilty guilty incarcerated lnsent lnfine  {

		gen `n'_up=`n'_ht+(1.96*`n'_se)
		gen `n'_down=`n'_ht-(1.96*`n'_se)
		gen `n'_pctfmt = string(100 * `n'_pct, "%8.0f") + "%"
		replace  `n'_pctfmt="("+`n'_pctfmt + ")"
	}

	gen type=1 if incarcerated_type=="Uncond"
	replace type=2 if incarcerated_type=="Case"
	replace type=3 if incarcerated_type=="Atty"
	replace type=4 if incarcerated_type=="Cond"

	label def typelabel 1 "Uncond. Penalty" 2 "Case Chars." 3 "Attorney Chars." 4 "Residual Penalty"

	label values type typelabel

	foreach outc in reduced dismissed defadj plead_nolo plead_guilty guilty incarcerated lnsent lnfine  {
		format `outc'_ht %12.2f 
	}

	#delimit ;
	set scheme s1mono;
	foreach outc in reduced dismissed defadj plead_nolo plead_guilty guilty incarcerated lnsent lnfine  {;
		
		sum `outc'_pct , meanonly;
		local label=r(mean);
		
		twoway bar `outc'_ht type if incarcerated_type=="Case" | incarcerated_type=="Atty" ,
			xlabel(1 2 3 4 , valuelabel ) || 
			bar `outc'_ht type if incarcerated_type=="Uncond"    || 
			bar `outc'_ht type if incarcerated_type=="Cond"   ||
			scatter  `outc'_ht type  if type!=1 , msym(none) mlab(`outc'_pctfmt) mlabpos(1) ||
			scatter  `outc'_ht type, msym(none) mlab(`outc'_ht) mlabpos(11) ||
			rcap `outc'_up `outc'_down type, lcolor(black) mcolor(black) ,
			legend(off)
			title(``outc'_title')
			ytitle("Assigned Counsel Penalty")
			xtitle("");
			graph save FigureGelbach_`outc'.gph, replace;
	};

#delimit cr		
	
import excel using FigureGelbach_CaseLength, first clear

	local caselength_title "Case Length"
	local _0_title "Case Length | Detained"
	local _1_title "Case Length | Released"
		
	foreach n in caselength _0 _1  {

	gen `n'_up=`n'_ht+(1.96*`n'_se)
	gen `n'_down=`n'_ht-(1.96*`n'_se)
	 gen `n'_pctfmt = string(100 * `n'_pct, "%8.0f") + "%"
	 replace  `n'_pctfmt="("+`n'_pctfmt + ")"
	}

	gen type=1 if caselength_type=="Uncond"
	replace type=2 if caselength_type=="Case"
	replace type=3 if caselength_type=="Atty"
	replace type=4 if caselength_type=="Cond"

	label def typelabel 1 "Uncond. Penalty" 2 "Case Chars." 3 "Attorney Chars." 4 "Residual Penalty"

	label values type typelabel

	foreach outc in caselength _0 _1  {
		format `outc'_ht %12.2f 
	}

	# delimit;
	set scheme s1mono;
	foreach outc in caselength _0 _1  {;
		
		sum `outc'_pct , meanonly;
		local label=r(mean);
		
		twoway bar `outc'_ht type if caselength_type=="Case" | caselength_type=="Atty" ,
			xlabel(1 2 3 4 , valuelabel ) || 
			bar `outc'_ht type if caselength_type=="Uncond"    || 
			bar `outc'_ht type if caselength_type=="Cond"   ||
			scatter  `outc'_ht type  if type!=1 , msym(none) mlab(`outc'_pctfmt) mlabpos(1) ||
			scatter  `outc'_ht type, msym(none) mlab(`outc'_ht) mlabpos(11) ||
			rcap `outc'_up `outc'_down type, lcolor(black) mcolor(black) ,
			legend(off)
			title(``outc'_title')
			ytitle("Assigned Counsel Penalty")
			xtitle("");
			graph save FigureGelbach_CaseLength.gph, replace;
	};

log close;




 
